package com.igd.socket.sdk.nio.multi_reactor;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

public class SubSelector implements Runnable {
	
	private Selector selector;
	
	public SubSelector(Selector selector) {
		this.selector = selector;
	}

	@Override
	public void run() {
		/**
		 * 循环获取连接或读，既负责读写请求
		 */
		while(true) {
			try {
				selector.select();
				Iterator<SelectionKey> keysItr = selector.selectedKeys().iterator();
				while(keysItr.hasNext()) {
					SelectionKey sKey =	keysItr.next();
					if(sKey.isWritable() || sKey.isReadable()) {
						System.out.println("isAcceptable："  + sKey.isAcceptable() + " isConnectable：" + sKey.isConnectable() + " isReadable：" + sKey.isReadable() + " isValid：" + sKey.isValid());
						// 该步骤是同步的处理，具体的业务逻辑的快慢会影响下一个selector.select()的获取，特别是WorkHandler的业务处理，可在WorkHandler内部使用线程池
						Runnable runnable = (Runnable)sKey.attachment();
						runnable.run();
					}
					keysItr.remove();	
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
	}

}
